package cn.goktech.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;

import cn.goktech.entity.Blog;
import cn.goktech.entity.Comment;
import cn.goktech.service.IBlogService;
import cn.goktech.service.ICommentService;
import cn.goktech.service.impl.BlogServiceImpl;
import cn.goktech.service.impl.CommentServiceImpl;
import cn.goktech.utils.PageDAO;

@WebServlet("/BlogServlet")
public class BlogServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String task = request.getParameter("task");

		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession();

		IBlogService blogService = new BlogServiceImpl();

		if ("queryBlog".equals(task)) {
			String title = request.getParameter("title");
			Blog blog = new Blog();
			blog.setTitle(title);

			// 分页
			PageDAO pageDAO = new PageDAO(request);
			// 总记录数
			int rscount = blogService.queryForCount(blog);
			// System.out.println("总记录数:"+rscount);
			pageDAO.setRscount(rscount);
			// 开始行
			int startLine = (pageDAO.getCurrentPage() - 1) * pageDAO.getPagesize();
			List<Blog> blogList = blogService.queryBlogByKey(blog, startLine, pageDAO.getPagesize());
			List<String> list = new ArrayList<>();
			for (Blog blog2 : blogList) {
				String string = removeHtmlTag(blog2.getContent());
				list.add(string);
				request.setAttribute("content", list);
			}

			
			String pageTools = pageDAO.pagetool(PageDAO.BbsImage);

			request.setAttribute("pageTools", pageTools);
			request.setAttribute("blogList", blogList);

			List<Blog> newblogList = blogService.newBlogList();
			request.setAttribute("newblogList", newblogList);

			List<Blog> hotblogList = blogService.hotBlogList();
			request.setAttribute("hotblogList", hotblogList);

			request.getRequestDispatcher("index.jsp").forward(request, response);
		} else if ("updateCount".equals(task)) {
			int id = Integer.parseInt(request.getParameter("id"));
			Blog blog = blogService.queryBlog(id);
			int count = blog.getCount();
			blog.setCount(count + 1);
			blogService.updateBlogCount(blog);
			String string = JSON.toJSONString(blog.getCount());
			out.print(string);
		} else if ("queryBlogById".equals(task)) {

			List<Blog> newblogList = blogService.newBlogList();
			request.setAttribute("newblogList", newblogList);

			List<Blog> hotblogList = blogService.hotBlogList();
			request.setAttribute("hotblogList", hotblogList);

			int id = Integer.parseInt(request.getParameter("id"));

			Blog blog = blogService.queryBlog(id);
			request.setAttribute("blog", blog);

			request.getRequestDispatcher("blogDetail.jsp").forward(request, response);

		} else if ("queryMyBlog".equals(task)) {
			String author = (String) session.getAttribute("users");// 获取当前登录的用户名
			Blog blog = new Blog();
			blog.setAuthor(author);
			String status = request.getParameter("status");
			if(status==null){
			blog.setStatus(1);
			}else if(status!=null){
				blog.setStatus(Integer.parseInt(status));
			}
			// 分页
			PageDAO pageDAO = new PageDAO(request);
			// 总记录数
			int rscount = blogService.queryForMyCount(blog);
			// System.out.println("总记录数:"+rscount);
			pageDAO.setRscount(rscount);
			// 开始行
			int startLine = (pageDAO.getCurrentPage() - 1) * pageDAO.getPagesize();
			List<Blog> myblogList = blogService.queryMyBlogList(blog, startLine, pageDAO.getPagesize());
			List<String> list = new ArrayList<>();
			for (Blog blog2 : myblogList) {
				String string = removeHtmlTag(blog2.getContent());
				list.add(string);
				request.setAttribute("content", list);
			}

			String pageTools = pageDAO.pagetool(PageDAO.BbsImage);

			request.setAttribute("pageTool", pageTools);
			request.setAttribute("myblogList", myblogList);

			List<Blog> newblogList = blogService.newBlogList();
			request.setAttribute("newblogList", newblogList);

			List<Blog> hotblogList = blogService.hotBlogList();
			request.setAttribute("hotblogList", hotblogList);

			request.getRequestDispatcher("user/myblog.jsp").forward(request, response);
		} else if ("queryOtherBlog".equals(task)) {
			String author = (String) request.getParameter("author");// 获取当前登录的用户名
			session.setAttribute("reqUser", author);
			Blog blog = new Blog();
			blog.setAuthor(author);
			blog.setStatus(1);

			// 分页
			PageDAO pageDAO = new PageDAO(request);
			// 总记录数
			int rscount = blogService.queryForMyCount(blog);
			// System.out.println("总记录数:"+rscount);
			pageDAO.setRscount(rscount);
			// 开始行
			int startLine = (pageDAO.getCurrentPage() - 1) * pageDAO.getPagesize();
			List<Blog> myblogList = blogService.queryMyBlogList(blog, startLine, pageDAO.getPagesize());
			List<String> list = new ArrayList<>();
			for (Blog blog2 : myblogList) {
				String string = removeHtmlTag(blog2.getContent());
				list.add(string);
				request.setAttribute("content", list);
			}
			
			String pageTools = pageDAO.pagetool(PageDAO.BbsImage);

			request.setAttribute("pageTool", pageTools);
			request.setAttribute("myblogList", myblogList);

			List<Blog> newblogList = blogService.newBlogList();
			request.setAttribute("newblogList", newblogList);

			List<Blog> hotblogList = blogService.hotBlogList();
			request.setAttribute("hotblogList", hotblogList);

			request.getRequestDispatcher("user/myblog.jsp").forward(request, response);
		} else if ("addBlog".equals(task)) {
			String author = request.getParameter("author");
			String type = request.getParameter("type");
			String title = request.getParameter("title");
			String content = request.getParameter("content");
			Date date = new Date();
			int status = Integer.parseInt(request.getParameter("status"));
			Blog blog = new Blog();
			blog.setAuthor(author);
			blog.setTitle(title);
			blog.setType(type);
			blog.setContent(content);
			blog.setDate(date);
			blog.setStatus(status);
			String action = request.getParameter("action");
			if(action==null){
				int insertBlog = blogService.insertBlog(blog);
				if (insertBlog > 0) {
					if(blog.getStatus()==1){
						out.println("<script>alert('发表成功');window.location.href='BlogServlet?task=queryMyBlog'</script>");
					}else{
						out.println("<script>alert('已保存至草稿箱');window.location.href='BlogServlet?task=queryMyBlog&status=0'</script>");
					}
				} else {
					out.println("<script>alert('发表失败');window.location.href='BlogServlet?task=queryMyBlog'</script>");
				}
			}else if("update".equals(action)){
				
				int id=Integer.parseInt(request.getParameter("id"));
				blog.setId(id);
				int update = blogService.updateBlog(blog);
				if (update > 0) {
					if(blog.getStatus()==1){
						out.println("<script>alert('发表成功');window.location.href='BlogServlet?task=queryMyBlog'</script>");
					}else{
						out.println("<script>alert('已保存至草稿箱');window.location.href='BlogServlet?task=queryMyBlog&status=0'</script>");
					}
				} else {
					out.println("<script>alert('发表失败');window.location.href='BlogServlet?task=queryMyBlog'</script>");
				}
			}
			
		}else if ("delete".equals(task)){
			int id = Integer.parseInt(request.getParameter("id"));
			int deleteBlog = blogService.deleteBlog(id);
			if(deleteBlog>0){
				out.write("true");
			}else{
				out.write("false");
			}
		}else if ("toUpdateBlogById".equals(task)) {
			int id = Integer.parseInt(request.getParameter("id"));
			Blog blog = blogService.queryBlog(id);
			request.setAttribute("blog", blog);
			request.getRequestDispatcher("user/blog.jsp").forward(request, response);
		}else if ("queryBlogByType".equals(task)) {
			String author=(String) session.getAttribute("username");
			String type=request.getParameter("type");
			Blog blog = new Blog();
			blog.setType(type);
			blog.setAuthor(author);
			List<Blog> myblogList = blogService.queryBlogByType(blog);
			List<String> list = new ArrayList<>();
			for (Blog blog2 : myblogList) {
				String string = removeHtmlTag(blog2.getContent());
				list.add(string);
				request.setAttribute("content", list);
			}
			List<Blog> newblogList = blogService.newBlogList();
			request.setAttribute("newblogList", newblogList);

			List<Blog> hotblogList = blogService.hotBlogList();
			request.setAttribute("hotblogList", hotblogList);
			
			request.setAttribute("myblogList", myblogList);
			request.getRequestDispatcher("user/myblog.jsp").forward(request, response);
		}
	}

	public static String removeHtmlTag(String inputString) {
		if (inputString == null) {
			return null;
		}
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		java.util.regex.Pattern p_script;
		java.util.regex.Matcher m_script;
		java.util.regex.Pattern p_style;
		java.util.regex.Matcher m_style;
		java.util.regex.Pattern p_html;
		java.util.regex.Matcher m_html;
		try {
			// 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
			// 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签
			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签
			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签
			textStr = htmlStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return textStr;// 返回文本字符串
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
